package pers.xuyong.strive.datastruct.stack;

/**
 * 栈
 * 特点:先进后出
 *
 * @author billymac
 * @version 1.0
 * @date 17/6/5  下午2:36
 * @since JDK1.8
 */
public class Stack {

    private int[] stack;

    private int top = -1;

    private int size;

    public Stack() {
        this(10);
    }

    public Stack(int size) {
        this.size = size;
        stack = new int[size];
    }

    /**
     * 初始化栈
     */
    public void initStack() {
        initStack(10);
    }

    /**
     * 初始化栈
     * @param size
     */
    public void initStack(int size) {
        this.size = size;
        stack = new int[size];
    }

    /**
     * 判断栈是否为空
     * @return
     */
    public boolean isEmpty() {
        boolean flag = false;
        if(top == -1 || stack == null)
            flag = true;
        return flag;
    }

    /**
     * 判断是否栈满
     * @return
     */
    public boolean isStackFull() {
        boolean flag = false;
        if (top == size)
            flag = true;
        return flag;
    }

    /**
     * 进栈
     * @param value
     */
    public void push(int value) {
        if (isStackFull())
            throw new IndexOutOfBoundsException("stack full !");

        int index = top;
        while(index > 0) {
            stack[index + 1] = stack[index];
            index -- ;
        }

        stack[0] = value;
        top++;
    }

    /**
     * 出栈
     * @return
     */
    public Integer pop() {
        if (isEmpty())
            return null;

        int value = stack[0];
        for (int i = 1; i <= top; i++) {
            stack[i - 1] = stack[i];
        }
        top--;
        return value;
    }

}
